package leetcode.pre100;

import java.util.LinkedList;
import java.util.List;

/**
 * 从左到右，从上到下，旋转打印矩阵【要求】 额外空间复杂度为O(1)
 *
 * 其他类似题目{@link baseclass.c_globalToPartMatrix.Code01_PrintMatrix}
 * 其他类似题目{@link baseclass.c_globalToPartMatrix.Code02_Rotate90}
 * 其他类似题目{@link baseclass.c_globalToPartMatrix.Code03_ZigZagPrintMatrix}
 * 其他类似题目{@link baseclass.c_matrix.FindMaxOrMinInMatrix}
 * @date 2020/2/27 22:11
 */
public class Code54_PrintMatrix_螺旋矩阵 {
    public static void main(String[] args) {
//        int[][]m = {{1,2,3},{4,5,6},{7,8,9}};
//        int[][]m = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
        int[][] m = {{1, 2, 3, 4, 0}, {5, 6, 7, 8, 0}, {9, 10, 11, 12, 0},
                {13, 14, 15, 16, 0}};
        spiralOrderPrint(m);
    }

    public static List<Integer> spiralOrderPrint(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return new LinkedList<>();
        }
        int a = 0;
        int b = 0;
        //矩阵的行数
        int c = matrix.length - 1;
        //矩阵的列数
        int d = matrix[0].length - 1;
        //左上角 始终不能超 右下角
        List<Integer> res = new LinkedList<>();
        while (a <= c && b <= d) {
            print(matrix, a++, b++, c--, d--,res);
        }
        return res;
    }
    public static void print(int[][] m, int a, int b, int c, int d, List<Integer> res) {
        //只有一行
        if(a == c){
            for (int i = b; i <= d ; i++) {
//                System.out.println(m[a][i]);
                res.add((m[a][i]));
            }
            return;
        }
        //只有一列
        if(b == d){
            for (int i = a; i <= c ; i++) {
//                System.out.println(m[i][b]);
                res.add((m[i][b]));
            }
            return;
        }
        int curCol = b;
        //从左到右
        for (; curCol < d; curCol++) {
//            System.out.println(m[a][curCol]);
            res.add((m[a][curCol]));
        }
        //从上到下
        int curRow = a;
        for (; curRow < c; curRow++) {
//            System.out.println(m[curRow][d]);
            res.add((m[curRow][d]));
        }
        //从右到左
        for (curCol = d; curCol > b; curCol--) {
//            System.out.println(m[c][curCol]);
            res.add((m[c][curCol]));
        }
        //从下到上
        for (curRow = c; curRow > a; curRow--) {
//            System.out.println(m[curRow][b]);
            res.add((m[curRow][b]));
        }
    }
}
